package com.party.web.web.controller.activity;

import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.ActStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.CounterfoilType;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.log.BehaviorType;
import com.party.core.model.member.*;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.member.IMemberActService;
import com.party.core.service.member.IMemberInfoService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.IThirdPartyUserService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.system.ISysRoleService;
import com.party.web.biz.activity.MemberActBizService;
import com.party.web.biz.file.ExcelExportService;
import com.party.web.biz.member.CIntegralBizToService;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.annotation.UserOperate;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.activity.MemberActOutput;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/activity/memberAct")
public class MemberActController {

    @Autowired
    private IActivityService activityService;
    @Autowired
    private IMemberActService memberActService;
    @Autowired
    private MemberActBizService memberActBizService;
    @Autowired
    private ExcelExportService excelExportService;
    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;
    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private IPartnerMemberService partnerMemberService;

    @Autowired
    private IThirdPartyUserService thirdPartyUserService;

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private CIntegralBizToService integralBizToService;

    protected static Logger logger = LoggerFactory.getLogger(MemberActController.class);

    public static final Integer NOT_BIND_PHONE = 1;

    public static final Integer YES_BIND_PHONE = 0;

    //行知公社会员
    public static final Integer XZGS_MEMBER = 1;

    /**
     * 报名列表
     *
     * @param memberAct
     * @param page
     * @param distributionId
     * @param commonInput
     * @return
     */
    @DataControl
    @RequestMapping(value = "memberActList")
    public ModelAndView memberActList(@ControlParam(table = "activity", column = "member", getMethodName = "getActId") MemberAct memberAct, Page page, @RequestParam(required = false) String distributionId, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("activity/memberActList");
        page.setLimit(10);
        memberAct.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        if (StringUtils.isNotEmpty(memberAct.getActId())) {
            Activity activity = activityService.get(memberAct.getActId());
            mv.addObject("activity", activity);

            GatherProject gatherProject = gatherProjectBizService.getProjectByTargetId(memberAct.getActId());
            mv.addObject("gatherProject", gatherProject);
        }

        Map<String, Object> params = CommonInput.appendParams(commonInput);
        params.put("distributionId", distributionId);
        Map<Integer, String> checkStatus = ActStatus.convertMap();
        checkStatus.put(ActStatus.ACT_STATUS_PAID.getCode(), "报名成功");

        List<WithBuyer> memberActs = memberActService.withMemberList(memberAct, params, page);
        List<MemberActOutput> memberActOutputs = LangUtils.transform(memberActs, input -> {
            MemberActOutput output = MemberActOutput.transform(input);
            String memberId = input.getMemberId();
            List<ThirdPartyUser> userList = thirdPartyUserService.getByMemberId(memberId);
            if (userList != null && userList.size() > 0)
            {
                if (input.getIsBindphone() != YES_BIND_PHONE)
                {
                    output.setIsBindphone(YES_BIND_PHONE);
                    //进行了微信授权登录
                    input.setIsBindphone(YES_BIND_PHONE);
                    memberActService.update(input);
                }
            }
            if (XZGS_MEMBER.equals(input.getIsXzgsMember())) {
                output.setIsXzgsMember(XZGS_MEMBER);
            }
            output.setCounterName(input.getCounterfoilName());
            output.setCounterType(input.getCounterfoilType() != null ? input.getCounterfoilType().toString() : "");
            output.setCounterPrice(input.getPayment());
            return output;
        });

        //判断是否有行知公社的权限
        String memberId = RealmUtils.getCurrentUser().getId();
        //是否拥有行知公社权限
        boolean isCommune = integralBizToService.isXZGSJurisdiction(memberId);

        mv.addObject("isCommune", isCommune);
        mv.addObject("isXzgsAdmin", RealmUtils.getNewCurrentUser().isXzgsAdmin());
        mv.addObject("page", page);
        mv.addObject("input", commonInput);
        mv.addObject("checkStatus", checkStatus);
        mv.addObject("distributionId", distributionId);
        mv.addObject("memberActs", memberActOutputs);
        mv.addObject("memberAct", memberAct);
        return mv;
    }

    /**
     * 线下付款 手动设置已付款
     * @param memberAct
     * @return
     */
    @ResponseBody
    @RequestMapping("verify2")
    public AjaxResult verify2(MemberAct memberAct) {
        if (StringUtils.isNotEmpty(memberAct.getId())) {
            MemberAct dbMemberAct = memberActService.get(memberAct.getId());
            dbMemberAct.setRemarks(memberAct.getRemarks());
            dbMemberAct.setPayStatus(MemberAct.PAY_STATUS_YES);
            memberActService.update(dbMemberAct);

            try {
                String actId = dbMemberAct.getActId();
                Activity act = activityService.get(actId);
//                memberPersonalCountBizService.updateActivityNumMoney(act.getMember(), dbMemberAct.getMemberId(), dbMemberAct.getPayment(), true);
                PartnerMember partnerMember = partnerMemberService.findByPartnerAndMember(act.getMember(), dbMemberAct.getMemberId());
                memberPersonalCountBizService.countOne(partnerMember);
            } catch (Exception e) {
                logger.error("实时更新个人统计活动数量/金额异常", e);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("审核失败");
    }

    /**
     * 审核退款
     *
     * @param checkStatus 审核状态
     * @param ids         id
     * @return
     */
    @ResponseBody
    @UserOperate(moduleName = "活动管理-报名管理", behaviorType = BehaviorType.REFUND)
    @RequestMapping(value = "verifyRefund")
    public AjaxResult verifyRefund(Integer checkStatus, String ids) {
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error("id不能为空");
        }
        if (null == checkStatus) {
            return AjaxResult.error("审核状态不能为空");
        }
        return verifyMethod(checkStatus, ids);
    }

    /**
     * @param checkStatus 审核状态
     * @param ids         id
     * @return
     * @Author yifeng
     * @Description 审核
     * @Date 16:11 2019/6/4
     **/
    @ResponseBody
    @RequestMapping(value = "verify")
    public AjaxResult verify(Integer checkStatus, String ids) {
        if (StringUtils.isEmpty(ids)) {
            return AjaxResult.error("id不能为空");
        }
        if (null == checkStatus) {
            return AjaxResult.error("审核状态不能为空");
        }
        return verifyMethod(checkStatus, ids);
    }


    /**
     * @param signinStatus 签到状态
     * @param id         id
     * @return
     * @Description 手动修改签到状态
     * @Date 16:11 2019/6/4
     **/
    @ResponseBody
    @RequestMapping(value = "updateSigninStatue")
    public AjaxResult updateSigninStatue(Integer signinStatus, String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        if (null == signinStatus) {
            return AjaxResult.error("签到状态不能为空");
        }
        MemberAct entity = memberActService.get(id);
        entity.setSignin(signinStatus);
        boolean flag = memberActService.update(entity);
        if (!flag)
        {
            return AjaxResult.error("修改签到状态失败");
        }
        return AjaxResult.success();
    }

    public AjaxResult verifyMethod(Integer checkStatus, String ids) {
        Map<String, String> errorMap = Maps.newHashMap();
        Integer totalCount = 0;
        Integer successCount = 0;
        for (String id : ids.split(",")) {
            try {
                if (StringUtils.isEmpty(id)) {
                    continue;
                }
                totalCount++;

                boolean flag = true;
                MemberAct entity = memberActService.get(id);
                if (null == entity) {
                    errorMap.put(id, "数据不存在");
                    continue;
                } else if (ActStatus.ACT_STATUS_AUDIT_PASS.getCode().equals(checkStatus)) {
                    // 审核通过
                    if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(entity.getCheckStatus())) {
                        // 新的处理方式 免费的活动不生成订单
                        if (entity.getCounterfoilType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                                entity.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
                            flag = memberActBizService.verifyPassFree(id, entity.getActId());
                        } else {
                            flag = memberActBizService.verifyPassNoFree(id, entity.getActId());
                        }
                    } else {
                        errorMap.put(id, "当前会员报名状态:" + ActStatus.getValue(entity.getCheckStatus()));
                        continue;
                    }
                } else if (ActStatus.ACT_STATUS_AUDIT_REJECT.getCode().equals(checkStatus)) {
                    // 审核拒绝
                    if (ActStatus.ACT_STATUS_AUDITING.getCode().equals(entity.getCheckStatus())
                            || ActStatus.ACT_STATUS_PAID.getCode().equals(entity.getCheckStatus())) {
                        // 新的处理方式 免费的活动不生成订单
                        if (entity.getCounterfoilType().equals(CounterfoilType.TYPE_FREE.getCode()) ||
                                entity.getCounterfoilType().equals(CounterfoilType.TYPE_OFF_LINE.getCode())) {
                            flag = memberActBizService.verifyFailFree(id, entity.getActId());
                        } else {
                            flag = memberActBizService.verifyFailNoFree(id);
                        }
                    } else {
                        errorMap.put(id, "当前会员报名状态:" + ActStatus.getValue(entity.getCheckStatus()));
                        continue;
                    }
                }
                if (flag) {
                    successCount++;
                } else {
                    errorMap.put(id, "审核异常");
                    continue;
                }
            } catch (Exception e) {
                errorMap.put(id, "审核异常");
                continue;
            }
        }
        Integer errorCount = errorMap.size();
        if (totalCount > 0 && errorCount == 0) {
            return AjaxResult.success("审核成功");
        } else if (totalCount > 0 && errorCount > 0) {
            Map<String, Object> returnMap = Maps.newHashMap();
            returnMap.put("totalCount", totalCount);
            returnMap.put("successCount", successCount);
            returnMap.put("errorCount", errorCount);
            returnMap.put("errorMap", errorMap);
            return AjaxResult.error("审核失败", returnMap);
        }
        return AjaxResult.error("审核失败");
    }

    @DataControl
    @ResponseBody
    @RequestMapping(value = "export")
    public AjaxResult exportFile(@ControlParam(table = "activity", column = "member", getMethodName = "getActId") MemberAct memberAct, CommonInput commonInput) {
        try {
            Activity activity = activityService.get(memberAct.getActId());
            String fileName = activity.getTitle() + "活动报名人员.xlsx";
            Map<String, Object> params = CommonInput.appendParams(commonInput);

            List<WithBuyer> memberActs = memberActService.withMemberList(memberAct, params, null);
            List<MemberActOutput> memberActOutputs = LangUtils.transform(memberActs, input -> {
                MemberActOutput output = MemberActOutput.transform(input);
                MemberInfo memberInfo = memberInfoService.findByMemberId(input.getMemberId());
                if(null != memberInfo) {
                    output.setIdCard(memberInfo.getIdCard());
                }
                output.setActivityTitle(activity.getTitle());
                output.setCreateTime(input.getCreateDate());
                output.setCounterName(input.getCounterfoilName());
                output.setCounterPrice(input.getPayment());
                output.setCounterType(CounterfoilType.getValue(input.getCounterfoilType()));
                // 票据为线下付款
                if (CounterfoilType.TYPE_OFF_LINE.getCode().equals(input.getCounterfoilType())) {
                    // 已付款
                    if (MemberAct.PAY_STATUS_YES.equals(input.getPayStatus())) {
                        output.setCheckStatusName("报名成功，已支付");
                    } else if (MemberAct.PAY_STATUS_NO.equals(input.getPayStatus())) {
                        output.setCheckStatusName("报名成功，未支付");
                    }
                } else {
                    output.setCheckStatusName(ActStatus.getValue(input.getCheckStatus()));
                }
                if (null == input.getSignin() || input.getSignin().equals(YesNoStatus.NO.getCode())) {
                    output.setSignInName("未签到");
                } else {
                    output.setSignInName("已签到");
                }
                return output;
            });
            SXSSFWorkbook workbook = memberActBizService.exportExcel(memberActOutputs, memberAct.getActId());
            String allPath = excelExportService.getExcelPath(fileName, "memberAct", new ExportExcel(), workbook);
            return AjaxResult.success((Object) allPath);
        } catch (Exception e) {
            logger.error("活动报名人员导出异常", e);
        }
        return AjaxResult.error("导出异常");
    }
}
